package handler

import (
	"github.com/gin-gonic/gin"
	"img-sys/model"
	"strconv"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	img := c.PostForm("img")
	content := c.PostForm("content")
	data := model.Book{
		Img:     img,
		Title:   title,
		Content: content,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	size, _ := strconv.Atoi(c.DefaultPostForm("size", "3"))
	offset := (page - 1) * size

	var book []model.Book
	err := model.DB.Offset(offset).Limit(size).Find(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取数据失败",
		})
		return
	}
	var count int64
	err = model.DB.Model(&model.Book{}).Count(&count).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取数据失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "获取成功",
		"data": gin.H{
			"book":  book,
			"count": count,
		},
	})

}
